#include "config.h"
#include <assert.h>
#include <string.h>
#include <stdio.h>
#include <errno.h>

#ifdef __cplusplus
extern "C" {
#endif

int serverconfig_load (const char* filename, serverconfig* conf)
{
  FILE * f = 0;
  int error = 0;
  assert(conf != 0);
  assert(filename != 0);
  printf("%s\n", filename);
  f = fopen(filename, "r");
  if (f == 0)
    goto error;
    
  error = fread(conf, sizeof(*conf), 1, f) == 0;
  if (error && ferror(f) && errno != 0)
    goto error;
  
  fclose(f);
  
  return 0;
  
  error:
    perror("Error reading config file");
    if (f)
      fclose(f);
    return 1;
}
int serverconfig_save (const char* filename, const serverconfig* conf)
{
  FILE * f = 0;
  int error = 0;
  assert(conf != 0);
  assert(filename != 0);
  
  f = fopen(filename, "w");
  printf("%s\n", filename);
  error = (fwrite(conf, sizeof(*conf), 1, f) == 0);
  if (!error && ferror(f) && errno != 0)
    perror("Error writing config file");
  
  fclose(f);
  
  return (error != 0);
}

int serverconfig_setroot (serverconfig* conf, const char* rootpath)
{
  assert(conf != 0);
  assert(rootpath != 0);
  
  if (strlen(rootpath) >= PATH_SIZE)
    return 1; 
  
  strcat(conf->root, rootpath);
  
  return 0;
}

#ifdef __cplusplus
}
#endif